package batch.flashgame;

import java.util.*;
import java.io.*;
import java.sql.*;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.*;

import batch.common.db.*;
import batch.common.report.*;

public class FlashGameFix
{
    private final String TODAY       = DateFormatUtils.format(new Date(), "yyyyMMdd");  //Get Current Date
    private final String MAILSUBJECT = "FlashGame FIX Fail(" + TODAY + ")";
    private final String FILEPATH    = "/home01/sfc/batch/flashgame/data/";

    private StringBuffer sql = new StringBuffer();

    public FlashGameFix(){
        ;
    }
    
    public static void main(String[] args){
        FlashGameFix fg = new FlashGameFix();
        
        Logger.getLogger("flashgame.flashgamefix").info("******************* START ***********************");
        fg.start(args[0]);
        Logger.getLogger("flashgame.flashgamefix").info("******************* E N D ***********************");
    }

    public void start(String fileNM){
        Connection conn = null;
        
        try{
            ArrayList arrL = this.readFile(fileNM);
    
            int cnt = (arrL == null)? 0 : arrL.size();
            
            conn = ConnectionManager.getConnection();
            conn.setAutoCommit(false);
    
            for(int i=0; i<cnt; i++){
                String strRank = (String)arrL.get(i);
                String[] rank = StringUtils.splitPreserveAllTokens(strRank, "||");
                String point_code = (rank[7].equals("W"))? "00701" : "00702";
                int point_nm = (rank[7].equals("W")) ? 100 : 500;
    
                if(insertRank(conn, rank)){
                    if(updatePoint(conn, rank[3], point_code, rank[4], point_nm) != 0){
                        throw new Exception("updatePoint Error");
                    }
                }
                else{
                    throw new Exception("rank Insert Error");
                }
            }
        }
        catch(FileNotFoundException fex){
            fex.printStackTrace();
            
            Logger.getLogger("flashgame.flashgamefix").info(fex.toString());
            StackTraceElement[] stElement = fex.getStackTrace();
            for(int p=0; p<stElement.length;p++){
                Logger.getLogger("flashgame.flashgamefix").info(stElement[p].toString());
            }
            
            //ReportError.byEmail(MAILSUBJECT, sqlex.toString());
        }
        catch(IOException ioex){
            ioex.printStackTrace();
            
            Logger.getLogger("flashgame.flashgamefix").info(ioex.toString());
            StackTraceElement[] stElement = ioex.getStackTrace();
            for(int p=0; p<stElement.length;p++){
                Logger.getLogger("flashgame.flashgamefix").info(stElement[p].toString());
            }
            
            //ReportError.byEmail(MAILSUBJECT, sqlex.toString());
        }
        catch(Exception ex){
            ex.printStackTrace();
            
            Logger.getLogger("flashgame.flashgamefix").info(ex.toString());
            StackTraceElement[] stElement = ex.getStackTrace();
            for(int p=0; p<stElement.length;p++){
                Logger.getLogger("flashgame.flashgamefix").info(stElement[p].toString());
            }
            
            Logger.getLogger("flashgame.flashgamefix").info("================= SQL ==========================");
            Logger.getLogger("flashgame.flashgamefix").info(sql.toString());
            Logger.getLogger("flashgame.flashgamefix").info("================= SQL ==========================");
            
            //ReportError.byEmail(MAILSUBJECT, sqlex.toString());
        }
        finally{
        }
    }


    public boolean insertRank(Connection conn, String[] rank) throws Exception {
        boolean result = false;
        
        PreparedStatement pstmt = null;
        
        sql.setLength(0);
        sql.append("INSERT INTO G_CO_FlashGame_BEST(RANKING_NUM  \n")
           .append("                              , GAME_ID      \n")
           .append("                              , USER_ID      \n")
           .append("                              , SITE_CD      \n")
           .append("                              , SCORE_NUM    \n")
           .append("                              , LEVEL_NUM    \n")
           .append("                              , RANKING_CD   \n")
           .append("                              , RANKING_YMD) \n")
           .append("                         VALUES(?            \n")
           .append("                              , ?            \n")
           .append("                              , ?            \n")
           .append("                              , ?            \n")
           .append("                              , ?            \n")
           .append("                              , ?            \n")
           .append("                              , ?            \n")
           .append("                              , ?)           \n");
           
        try{
            pstmt = conn.prepareStatement(sql.toString());
            
            pstmt.setString( 1, rank[1]);  //RANKING_NUM
            pstmt.setString( 2, rank[2]);  //GAME_ID
            pstmt.setString( 3, rank[3]);  //USER_ID
            pstmt.setString( 4, rank[4]);  //SITE_CD
            pstmt.setString( 5, rank[5]);  //SCORE_NUM
            pstmt.setString( 6, rank[6]);  //LEVEL_NUM
            pstmt.setString( 7, rank[7]);  //RANKING_CD
            pstmt.setString( 8, rank[8]);  //RANKING_YMD
            pstmt.executeUpdate();
            pstmt.close();
            
            result = true;
        }
        finally{            
            if(pstmt != null) try { pstmt.close(); } catch(Exception e) {}
        }
        
        return result;
    }

    public int updatePoint(Connection conn, String user_id, String point_code, String site_cd, int point_nm) throws Exception {
        int result = 0;
        
        sql.setLength(0);
        sql.append(" call  PointCountry_Pack.ChangePoint_MAIN(?,?,?,?,?,?) ");
        
        CallableStatement cs = null;
        
        try
        {
            cs = conn.prepareCall(sql.toString());
            cs.setString(1, user_id);
            cs.setString(2, point_code);
            cs.setString(3, site_cd);
            cs.setInt(4, point_nm);
            cs.setInt(5, 0);
            cs.registerOutParameter(6, 4);
            cs.execute();
            
            result = cs.getInt(6);
            
            if(result == 0){
                Logger.getLogger("flashgame.flashgamefix").info(site_cd + "--" + user_id + ":true");
            }
            else{
                Logger.getLogger("flashgame.flashgamefix").info(site_cd + "--" + user_id + ":false:" + result);
                Logger.getLogger("flashgame.flashgamefix").info("call  PointCountry_Pack.ChangePoint_MAIN(" + user_id + ", " + point_code + ", " + site_cd + ", " + point_nm);
            }
        }
        finally{
            if(cs != null) try { cs.close(); } catch(Exception e) {}
        }
        
        return result;
    }

    public ArrayList readFile(String fileNM) throws Exception {
        ArrayList arrL = new ArrayList();
                
        FileReader fReader = null;
        BufferedReader bReader = null;
        
        try{
            fReader = new FileReader(FILEPATH + fileNM);
            bReader = new BufferedReader(fReader);
            
            for(String s2 = ""; (s2 = bReader.readLine()) != null;)
                arrL.add(s2);
        }
        finally{
            if(fReader != null) try { fReader.close(); } catch(Exception ex) {}
            if(bReader != null) try { bReader.close(); } catch(Exception ex) {}
        }        
        
        return arrL;
    }
}
